// 这是一个分析器
import fs from 'fs'
import cheerio from 'cheerio'
import { Analyze } from './demo'
interface Course {
  title: string
  img: string
  count: string
}
interface CourseResult {
  time: number
  data: Course[]
}
interface Content {
  [propname: number]: Course[]
}
export default class Dellanalyzer implements Analyze {
  private static instance: Dellanalyzer
  static getInstance() {
    if (!this.instance) {
      this.instance = new Dellanalyzer()
    }
    return this.instance
  }
  private getCourseInfo(html: string) {
    const courseArr: Course[] = []
    const $ = cheerio.load(html)
    const courseItems = $('.course-item')
    courseItems.map((index, element) => {
      console.log('countcountcountcountcount')
      const descs = $(element).find('.course-desc').eq(0)
      const countele = $(element).find('.course-desc').eq(1)
      const image = $(element).find('.course-img').attr('src')
      const img = image!.split('.')[0]
      const title = descs.text()
      const count = countele.text().split('：')[1]
      console.log('countcountcountcountcount', count)
      courseArr.push({
        img,
        title,
        count,
      })
    })
    return {
      time: new Date().getTime(),
      data: courseArr,
    }
  }
  private generateJsonContent(courseRes: CourseResult, filePath: string) {
    let fileContent: Content = {}
    if (fs.existsSync(filePath)) {
      // 判断路径是否存在
      fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    }
    const { time, data } = courseRes
    fileContent[time] = data
    return fileContent
  }
  public analyze(html: string, filePath: string) {
    const courseInfo = this.getCourseInfo(html)
    const fileContent = this.generateJsonContent(courseInfo, filePath)
    return JSON.stringify(fileContent)
  }
  private constructor() {}
}
